/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Addon SDK dependencies */

/* Used modules */
const _iBrowserTab = require('./browser-tab');

/* Internal APIs */
const getTabs = sdkWindow => {
	const sdkTabs = new Set;
	const eventListeners = [];
	
	const sendEvent = (type, message) => {
		eventListeners.forEach(f => f(type, message));
	};
	
	return Object.freeze({__proto__: null
		,addEventListener (f) {
			eventListeners.push(f);
		}
		,open (uri) {
			return new Promise((resolve, reject) => {try {
				sdkWindow.tabs.open({__proto__: null
					,url: uri ? uri + '' : 'about:blank'
					,inBackground: true
					,onOpen (sdkTab) {try {
						sdkTabs.add(sdkTab);
						sendEvent('open', {__proto__: null});
						
						sdkTab.once('ready', sdkTab => {
							const iBrowserTab = _iBrowserTab;
							const wrapper = iBrowserTab.createSDKTabWrapper(sdkTab);
							wrapper.registerEventHandler((type, message) =>
								void(sendEvent(type, message)));
							resolve(wrapper);
						});
						
						sdkTab.on('ready', sdkTab =>
							void(sendEvent('ready', {__proto__: null
								,uri: sdkTab.url + ''})));
						
						sdkTab.on('close', sdkTab =>
							void(sdkTabs.delete(sdkTab)
								,sendEvent('close', {__proto__: null
									,uri: null})));
					} catch (e) {
						reject('' + e);
					}}
				});
			} catch (e) {
				reject('' + e);
			}});
		}
		,closeAllTabs () { // just close tabs
			sendEvent('closeAll', {__proto__: null});
			return new Promise((resolve, reject) => {try {
				let tabCount = sdkTabs.size;
				Array.from(sdkTabs).forEach(sdkTab => sdkTab.close(() => {
					tabCount--;
					if (tabCount < 1) {
						resolve(true);
					}
				}));
			} catch (e) {
				reject('' + e);
			}});
		}
	});
};

/* Exports */
exports.getTabs = getTabs;

// vim: ts=4 noet ai

